﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CamShared;
using System.Diagnostics;
using System.Windows.Forms;
using System.Threading;
using DavuxLib;

namespace CamServer
{
    public class SimpleViewer 
    {
        List<Viewer> Windows = new List<Viewer>();
        #region ICameraOutput Members

        public void FrameReceived(ICamera camera, System.Drawing.Image frame)
        {
            foreach (Viewer v in Windows)
            {
                if (v.Camera == camera && v.Visible)
                {
                    //v.OnFrame(frame);
                    return;
                }
            }
        }

        public void ErrorOccured(ICamera camera, string Error, bool Fatal)
        {
            foreach (Viewer v in Windows)
            {
                if (v.Camera == camera)
                {
                   // v.OnError(Error, Fatal);
                    return;
                }
            }
        }

        public void CameraAttached(ICamera camera)
        {
            // attach and open a new window

            if (Settings.Get(camera.Name + "|Show Viewer On Startup", false))
            {
                Thread t = new Thread(new ParameterizedThreadStart(OpenWindow));
                t.Start(camera);
            }
            //Settings.SetRestartRequired(camera.Name + "|Show Viewer On Startup");
        }

        private void OpenWindow(object cam)
        {
            Viewer v = new Viewer((ICamera)cam);
            Windows.Add(v);
            v.Show();
            Application.Run();
        }

        public string Name
        {
            get { return "Simple Viewer"; }
        }

        #endregion

        #region IDisposable Members

        public void Dispose()
        {
            foreach (Viewer v in Windows)
            {
                try
                {
                    if (v != null)
                    {
                        if (v.InvokeRequired)
                        {
                            v.BeginInvoke(new CloseWindow(CloseViewer), v);
                        }
                    }
                }
                catch (Exception)
                {

                }
            }
        }

        #endregion

        delegate void CloseWindow(Viewer v);

        void CloseViewer(Viewer v)
        {
            v.Close();
        }
    }
}
